
// 通用模块封装

const { createInterface } = require('readline/promises')

function validateProbabilityInput(args) {
  // 尝试将输入转换为逗号分隔的字符串
  let parsedProbabilities
  const commaSeparatedInput = args.join(',')
  if (commaSeparatedInput.includes(',')) {
    const splitInput = commaSeparatedInput.split(',')
    parsedProbabilities = splitInput.map(arg => Number(arg))
  } else {
    parsedProbabilities = args.map(arg => Number(arg))
  }

  let isValid = true
  let errors = []

  if (parsedProbabilities.length < 2) {
    isValid = false
    errors.push('命令行参数错误: 概率数据少于两个!\n')
    return { isValid, errors }
  }

  if (parsedProbabilities.some(isNaN) || parsedProbabilities.includes(0)) {
    isValid = false
    errors.push('请输入数字!')
    return { isValid, errors }
  }

  if (parsedProbabilities.some(p => p <= 0)) {
    isValid = false
    errors.push('请输入大于0的数!')
    return { isValid, errors }
  }
  if (parsedProbabilities.some(p => p >= 1)) {
    isValid = false
    errors.push('请输入小于1的数!')
    return { isValid, errors }
  }

  const totalProbability = parsedProbabilities.reduce((sum, p) => sum + p, 0)
  if (Math.abs(totalProbability - 1) < 1e-8) {
    isValid = true
    return { isValid, errors, probabilities: parsedProbabilities }
  }
  if (totalProbability > 1) {
    isValid = false
    errors.push('概率空间不封闭, 概率和大于1!')
    return { isValid, errors }
  } else {
    isValid = false
    errors.push('概率空间不封闭, 概率和小于1!')
    return { isValid, errors }
  }
  
}

function calculateEntropy(probabilities) {
  return probabilities.reduce((entropy, p) => {
    const probability = parseFloat(p)
    return entropy - probability * Math.log2(probability)
  }, 0)
}

async function interactiveInput() {
  const rl = createInterface({
    input: process.stdin,
    output: process.stdout
  })

  const probabilities = []
  let totalProbability = 0
  let isFirstInput = 1

  try {
    while (true) {
      let input
      if (isFirstInput === 1) {
        input = await rl.question(`P${probabilities.length}: `)
      } else {
        input = await rl.question("")
      }
      const probability = Number(input)
      if (isNaN(probability)) {
        console.log('请输入数字!')
        isFirstInput = 0
        continue
      }
      
      if (probability < 0) {
        console.log('请输入大于0的数!')
        isFirstInput = 0
        continue
      }

      if (probability > 1) {
        console.log('请输入小于1的数!')
        isFirstInput = 0
        continue
      }
      isFirstInput = 1

      probabilities.push(probability)
      totalProbability += probability

      if (totalProbability === 1 ||
      Math.abs(totalProbability - 1) < 0.00000000000001) {
        break
      }
    }
    return probabilities
  } finally {
    rl.close()
  }
}


module.exports = {
  validateProbabilityInput,
  calculateEntropy,
  interactiveInput
}
